package com.hefan.common.pay.apple;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hefan.common.util.PayPropertiesUtils;
import org.apache.commons.lang.StringUtils;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lxw on 2016/10/19.
 */
public class AppleAppStoreVerifyRequest {

    public static Map verifyReceipt(String reqUrl, String receiptDataJson, String appTransactionId) throws  Exception{
        int status = -1;
        String bid = "";
        String productId = "";
        String transactionId = "";
        //This is the URL of the REST webservice in iTunes App Store
        URL url = new URL(reqUrl);
        //make connection, use post mode
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setAllowUserInteraction(false);
        //Write the JSON query object to the connection output stream
        PrintStream ps = new PrintStream(connection.getOutputStream());
        ps.print(receiptDataJson);
        ps.close();
        //Call the service
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        //Extract response
        String str;
        StringBuffer sb = new StringBuffer();
        while ((str = br.readLine()) != null) {
            sb.append(str);
        }
        br.close();
        String response = sb.toString();
        //System.out.println("AppleAppStoreVerifyRequest----response:"+response);
        JSONObject resutl = JSON.parseObject(response);
        status = resutl.containsKey("status") ? resutl.getInteger("status") : status;
        JSONObject receipt = resutl.containsKey("receipt") ? resutl.getJSONObject("receipt") : null;
        if(receipt != null && !StringUtils.isBlank(receipt.toString())){
            bid = receipt.containsKey("bundle_id") ? receipt.getString("bundle_id") : bid;
            JSONArray inApp =  receipt.getJSONArray("in_app");
            if(inApp != null && !StringUtils.isBlank(inApp.toString())) {
                if(StringUtils.isBlank(appTransactionId)) { //如果未给订单号，则默认获取第一个
                    JSONObject inAppJSONObjectTemp = inApp.getJSONObject(0);
                    if (inAppJSONObjectTemp != null && !inAppJSONObjectTemp.isEmpty()) {
                        productId = inAppJSONObjectTemp.containsKey("product_id") ? inAppJSONObjectTemp.getString("product_id") : productId;
                        transactionId = inAppJSONObjectTemp.containsKey("transaction_id") ? inAppJSONObjectTemp.getString("transaction_id") : transactionId;
                    }
                } else  { //如果APP已给定订单号时用订单号进行查找
                    for(int i=0; i<inApp.size(); i++) {
                        JSONObject inAppJSONObjectTemp = inApp.getJSONObject(i);
                        if (inAppJSONObjectTemp != null && !inAppJSONObjectTemp.isEmpty()) {
                            String transactionIdTemp = inAppJSONObjectTemp.containsKey("transaction_id") ? inAppJSONObjectTemp.getString("transaction_id") : transactionId;
                            if(appTransactionId.equals(transactionIdTemp)) {
                                productId = inAppJSONObjectTemp.containsKey("product_id") ? inAppJSONObjectTemp.getString("product_id") : productId;
                                transactionId = transactionIdTemp;
                            }
                        }
                    }
                }
            }
        }
        Map resMap = new HashMap();
        resMap.put("status",status);
        resMap.put("bid",bid);
        resMap.put("productId",productId);
        resMap.put("transactionId",transactionId);
        resMap.put("resutl",resutl == null ?"":resutl.toJSONString());
        return resMap;
    }

    public static void main(String[] args) {
        Map checkParamsMap = new HashMap();
        String url ="https://buy.itunes.apple.com/verifyReceipt";

        String [] strs  = {
                "MIIVcwYJKoZIhvcNAQcCoIIVZDCCFWACAQExCzAJBgUrDgMCGgUAMIIFFAYJKoZIhvcNAQcBoIIFBQSCBQExggT9MAoCARQCAQEEAgwAMAsCAQMCAQEEAwwBMzALAgETAgEBBAMMATMwCwIBGQIBAQQDAgEDMAwCAQ4CAQEEBAICAI0wDQIBCgIBAQQFFgMxNyswDQIBDQIBAQQFAgMBhwUwDgIBAQIBAQQGAgRGBHYZMA4CAQkCAQEEBgIEUDI0NzAOAgELAgEBBAYCBAcPhiswDgIBEAIBAQQGAgQw222CMBACAQ8CAQEECAIGUPYxOGpSMBQCAQACAQEEDAwKUHJvZHVjdGlvbjAYAgEEAgECBBBwpaPZv2V5M9GxFmHNtFN9MBwCAQUCAQEEFEDL10gB/AgeNPrQ0F4xWkvcAGylMB4CA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MMO0FwcGxlIFdvcmxkd2lkZSBEZXZlbG9wZXIgUmVsYXRpb25zIENlcnRpZmljYXRpb24gQXV0aG9yaXR5AggO61eH554JjTAJBgUrDgMCGgUAMA0GCSqGSIb3DQEBAQUABIIBAJoiLA8BKIOKneuuRSoZTNeoplzcv/kXzd6VOE4zSRu/NSTSw8oqJBZVLdQbQO2WyyuljoBcSJNtPyo2sFgQB7FdFGTKtivPKVQl5JHT+8qeo4pOJHofkTlH2tdelTap9IG+ANtKWyYUAtU6pBLf1wZGG0QznrWtOXYJplcRPoqQk0vgVE6LVYnKmmF0Gg7CVFF9xCruSCovbdmxrfdoc01fHDZM4G03NY2G0IfnskE3Ce09CKHkfLqdMXZjocNAHp5uMyYiTCoUZuMSwSytfbuBe2Akqtm3cgxtpjxRkWC4fgniNkWqvcazcle4P395Zt1xli/yGgWNwryt3EG/f8U="
                  };
        for (String str:strs) {
            checkParamsMap.put("receipt-data",str);
            String receiptDataJson = JSON.toJSONString(checkParamsMap);
            try {
                Map verifyMap = AppleAppStoreVerifyRequest.verifyReceipt(url, receiptDataJson,"123213");
                System.out.println(verifyMap.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
